package tomcat.connector;

import tomcat.Utils;

import java.io.*;

import static tomcat.Utils.getRequest;

/**
 * HTTP/1.1 200 OK
 */
public class Response {
    private static final int BUFFER = 2048;
    Request request;
    OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() throws IOException {
        File file = new File(ConnectorUtil.WEB_ROOT, request.getUri());
        try {
            writeResponse(file, HttpStatus.SC_OK);
        } catch (IOException e) {
            // e.printStackTrace();
            writeResponse(new File(ConnectorUtil.WEB_ROOT, "404.html"),
                    HttpStatus.SC_NOT_FOUND);
        }

    }

    private void writeResponse(File resource, HttpStatus status) throws IOException {
        // 会自动释放
        try(FileInputStream fis = new FileInputStream(resource)) {
            outputStream.write(ConnectorUtil.renderStatus(status).getBytes());
            byte[] buffer = new byte[BUFFER];
            int length = -1;
            while ((length = fis.read(buffer, 0, BUFFER)) != -1){
                System.out.println(length);
                outputStream.write(buffer,0,length);
            }
        }

    }

    public static void main(String[] args) throws IOException {
        String validRequest = "GET /index.html HTTP/1.1";
        String invalidRequest = "GET /a.html HTTP/1.1";
        String status100 = "HTTP/1.1 100 OK\r\n\r\n";
        String status404 = "HTTP/1.1 404 File NOT FOUND\r\n\r\n";

        // Request.sendRequest(validRequest);

        // Request.sendRequest(invalidRequest);

        // testValid(validRequest);
        testInvalid(invalidRequest);
    }

    private static void testValid(String validRequest) throws IOException {
        Request request = getRequest(validRequest);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Response response = new Response(outputStream);
        response.setRequest(request);
        response.sendStaticResource();

        String resource = Utils.readFileToString(ConnectorUtil.WEB_ROOT + request.getUri());
        System.out.println(resource);
        System.out.println(outputStream.toString());
    }

    private static void testInvalid(String validRequest) throws IOException {
        Request request = getRequest(validRequest);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Response response = new Response(outputStream);
        response.setRequest(request);
        response.sendStaticResource();

        String resource = Utils.readFileToString(ConnectorUtil.WEB_ROOT + "/404.html");
        System.out.println(resource);
        System.out.println(outputStream.toString());
    }
}
